/* 
 * Copyright (c) 2019, CENTRIN.CIYUN.LTD. All rights reserved.
 */
package com.cory.boot.component.mq;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 消息队列生产者
 * @author xiongcong
 * @date 2019-07-18
 */
@Configuration
@Slf4j
@ConditionalOnProperty(prefix = "rocketmq", value = {"namesrvAddr", "producerGroup"})
public class RocketMQProducer {
    @Autowired
    private RocketMQConf rocketMQConf;
    
    @Autowired
    private MQProducer producer;
    
    public void sendMsg(String topic, String tags, String jsonMsg) throws Exception {
        sendMsg(topic, tags, jsonMsg, null);
    }
    
    public void sendMsg(String topic, String tags, String jsonMsg, String keys) throws Exception {
        if (StringUtils.isNotEmpty(jsonMsg)) {
            Message msg = new Message(topic, tags, keys, jsonMsg.getBytes());
            SendResult result = producer.send(msg);
            log.debug("id:" + result.getMsgId() + " result:" + result.getSendStatus());
        }
    }

    @Bean
    protected DefaultMQProducer defaultProducer() throws MQClientException {
        log.info("rocketmq defaultProducer 正在开启---------------------------------------");
        
        DefaultMQProducer producer = new DefaultMQProducer(rocketMQConf.getProducerGroup());
        producer.setNamesrvAddr(rocketMQConf.getNamesrvAddr());
        producer.start();
        
        log.info("rocketmq defaultProducer 成功开启---------------------------------------");
        return producer;
    }
}
